<template>
    <div class="chat-container">
        <!-- Left side: User list -->
        <div class="left-side">
            <!-- Search input (moved outside) -->
            <div class="search-wrapper">
                <el-input v-model="searchUserName" placeholder="回车搜索用户" class="search-input" @keydown.enter.native="searchUserForForm"></el-input>
            </div>
            <!-- User list (with scroll) -->
            <el-scrollbar class="user-list-scroll">
                <el-row>
                    <el-col :span="24" v-for="form in messageForm" :key="form.sendUser.userId" @click.native="chooseUser(form.sendUser)" class="user-item" v-if="messageForm.length !== 0">
                        <div class="user-avatar-wrapper">
                            <div :class="form.isOnline==true?'online-dot': 'offline-dot'"></div>
                            <!-- Element UI Badge for showing unread messages -->
                            <el-badge :value="form.noReadMessageLength" class="message-badge" v-if="form.noReadMessageLength > 0">
                                <!-- <img :src="form.sendUser.avatar" class="user-avatar"> -->
                                <img src="../../icons/img/touxiang.png" class="user-avatar">
                            </el-badge>
                            <!-- <img :src="form.sendUser.avatar" class="user-avatar" v-else> -->
                            <img src="../../icons/img/touxiang.png" class=" user-avatar" v-else>

                        </div>
                        <div class="user-details">
                            <div class="user-name">{{ form.sendUser.userName }}</div>
                            <div class="user-last-message">{{ form.lastMessage }}&nbsp;</div>
                        </div>
                    </el-col>
                </el-row>
            </el-scrollbar>
        </div>
        <!-- Right side: Chat box -->
        <div class="right-side">
            <!-- Chat header -->
            <div class="chat-header">
                <span v-if="currentUser">{{ currentUser.userName }}</span>
            </div>
            <!-- Chat messages -->
            <el-scrollbar class="chat-messages" ref="messageContainer">
                <div class="messageBox" v-for="message in messages" :key="message.handle" :class="{ ownMessage: message.sendUser === loginUser.userId, otherMessage: message.sendUser !== loginUser.userId }">
                    <!-- <div><img :src="message.sendUser === loginUser.userId ? loginUser.avatar : currentUser.avatar" alt="" style="border: 1px solid #70c1fa;"></div> -->
                    <div><img src="../../icons/img/touxiang.png" alt="" style="border: 1px solid #70c1fa;"></div>
                    <div class="messageContent">{{ message.content }}</div>
                    <div class="messageTime">{{ message.createTime.replace('T', ' ') }}</div>
                </div>
            </el-scrollbar>
            <div class="chat-input">
                <el-input v-model="newMessage.content" placeholder="请输入聊天内容" autosize class="message-input" @keydown.enter.native="sendMessage"></el-input>
                <el-button type="primary" @click.native="sendMessage" class="send-button">发送</el-button>
            </div>
        </div>
    </div>
</template>
<script>
// 获取用户信息和聊天信息后端接口，根据自己的实际项目修改
import { findMessageBySendUserAndReceiveUser, searchUserForForm } from '../../api/message'
// 发送信息给指定userId的websocket
import { sendMessageTo } from '../../api/webSocketApi'
// 根据userId获取用户信息
import { searchUserByUserId } from '../../api/user'
// 刚刚写的websocket
import websocket from '@/utils/webSocket'
import { getLoginUserInfo } from '@/utils/userinfo'

export default {
    data() {
        return {
            currentUser: null, // 当前聊天的人
            loginUser: {},
            messages: [],
            messageForm: [], // 聊天所有信息
            newMessage: {
                handle: '',
                sendUser: '',
                receiveUser: '',
                content: '',
                is_read: '0',
                createTime: ''
            },
            searchUserName: ''
        }
    },
    mounted() {
        websocket.setMessageCallback((res) => {
            this.handleMessage(res)
        })
    },
    created() {
        const { loginUser } = this;
        // 获取登录用户userId,请根据自己实际项目获取
        this.loginUser = getLoginUserInfo()
        let userId = this.loginUser.userId
        this.connectWebSocket(userId)
        // if (userId) {
        //     console.log('searchUserByUserId--->', userId)
        //     searchUserByUserId(userId).then(res => {
        //         if (res.header.code === 0) {
        //             if (res.value) {
        //                 this.loginUser = res.value
        //             } else {
        //                 this.loginUser.userId = userId
        //             }
        //         }
        //     }).then(() => {
        //         this.searchUserForForm()
        //     })

        // }
        this.searchUserForForm()
    },
    beforeCreate() {

    },
    methods: {
        async fetchMessages(userId) {
            if (!userId) {
                this.searchUserForForm()
                return
            }
            if (this.loginUser.userId == null) {
                this.$message.error('登录用户id获取失败,请重新登录!')
                return
            }
            findMessageBySendUserAndReceiveUser(userId, this.loginUser.userId).then(async res => {
                await this.searchUserForForm()
                this.messages = res.data
                // 将聊天记录总下拉到最下方
                this.$nextTick(() => {
                    this.scrollToBottom()
                })
            })
        },
        sendMessage() {
            if (!this.newMessage.content.trim()) {
                this.$message.warning('请输入聊天内容')
                return
            }
            this.newMessage.content = this.newMessage.content.trim()
            if (this.loginUser.userId == null) {
                this.$message.error('登录用户编号获取失败,请重新登录!')
                return
            }
            if (this.loginUser.userId === this.currentUser.userId) {
                this.$message.error('不能给自己发送信息!')
                return
            }
            this.newMessage.sendUser = this.loginUser.userId
            this.newMessage.receiveUser = this.currentUser.userId
            this.sendWebSocketMessage(this.newMessage)
            sendMessageTo(this.newMessage).then(res => {
                this.chooseUser(this.currentUser)
                this.newMessage.content = null
            })
        },
        // 消息过多的时候滚动到最新消息位置
        scrollToBottom() {
            // 使用 $refs 来获取对消息容器的引用
            const container = this.$refs.messageContainer.$refs.wrap
            // 滚动到底部
            container.scrollTop = container.scrollHeight
        },
        checkAvatar(avatar) {
            if (avatar && avatar !== undefined) {
                return avatar
            }
            return ''
        },
        chooseUser(user) {
            this.currentUser = user
            this.fetchMessages(user.userId)
        },
        // websocket
        async connectWebSocket(userId) {
            await new Promise((resolve) => {
                websocket.Init(userId)

                // 在 WebSocket 连接成功时调用 resolve
                websocket.getWebSocket().onopen = () => {
                    console.log('WebSocket连接成功')
                    resolve()
                }
            })
        },
        // 发送信息
        sendWebSocketMessage(message) {
            websocket.Send(message)
            websocket.getWebSocket().onmessage = (event) => {
                // 处理消息，这里你可以根据实际需求更新页面上的数据
                console.log('收到的消息WebSocket2:', event)
                // 更新收到的消息
                // receivedMessage.value = event.data
                if (this.currentUser) {
                    this.fetchMessages(this.currentUser.userId)
                } else {
                    this.fetchMessages()
                }
            }
        },
        handleMessage(message) {
            // 内容进行相应的处理
            console.log('有新消息:', message)
            if (this.currentUser) {
                this.fetchMessages(this.currentUser.userId)
            } else {
                this.fetchMessages()
            }
        },
        // 获取所有信息
        searchUserForForm() {
            if (this.loginUser !== null) {
                searchUserForForm(this.loginUser.userId, this.searchUserName).then(res => {
                    console.log('res--->', res)
                    this.messageForm = res.data
                })
            }
        },
        // 初始化websocket
        async connectWebSocket(userId) {
            await new Promise((resolve) => {
                websocket.Init(userId)

                // 在 WebSocket 连接成功时调用 resolve
                websocket.getWebSocket().onopen = () => {
                    console.log('WebSocket连接成功1')
                    resolve()
                }
            })
        },
    },

}
</script>

<style scoped>
.chat-container {
    display: flex;
    height: 100%;
    background: linear-gradient(to bottom right, #ffffff, #eceff1);
}

.left-side {
    position: relative; /* Position relative for absolute positioning */
    flex: 1;
    padding: 20px;
    border-right: 1px solid #eaeaea;
    border-radius: 10px;
    height: 500px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-color: rgba(132, 49, 49, 0.05);
    /* backdrop-filter: blur(10px); */
}

.search-input {
    position: absolute;
    top: 20px;
    left: 20px;
    width: calc(100% - 40px);
    max-width: 300px;
}

.user-list-scroll {
    top: 40px;
    height: calc(100% - 40px);
    overflow-y: auto;
}

.user-avatar-wrapper {
    position: relative;
    display: inline-block;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid #74ffd2;
}

.user-name {
    font-weight: 800;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 溢出隐藏 */
    padding-left: 15px;
    text-overflow: ellipsis; /* 超出显示省略号 */
    text-align: left; /* 添加左对齐属性 */
}

.user-last-message {
    color: #a19f9f;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    padding-left: 15px;
    text-overflow: ellipsis;
    text-align: left; /* 添加左对齐属性 */
}

.right-side {
    flex: 3;
    display: flex;
    flex-direction: column;
    height: 600px;
}

.chat-header {
    padding: 20px;
    border-bottom: 1px solid #eaeaea;
    font-size: 1.2em;
    color: #37474f;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
}

.chat-input {
    padding: 20px;
    display: flex;
    align-items: center;
}

.message-input {
    flex: 1;
    margin-right: 10px;
}

.send-button {
    flex-shrink: 0;
}

.user-item {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #f0f0f2;
}

.user-item:hover {
    background-color: #e0e0e0;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.user-details {
    flex-grow: 1; /* 填充剩余空间 */
}

.messageBox {
    display: flex;
    align-items: flex-start; /* 将头像和文本第一行对齐 */
    margin-bottom: 10px;
}

.messageBox img {
    width: 40px; /* 调整头像大小 */
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    margin-left: 10px;
}

.messageContent {
    max-width: 70%; /* 调整发送信息宽度 */
    padding: 10px;
    border-radius: 8px;
    background-color: #f0f0f0;
    text-align: left; /* 文本左对齐 */
    word-wrap: break-word; /* 当文本过长时自动换行 */
}

.messageTime {
    font-size: 12px;
    color: #999;
    margin-left: 10px;
    margin-top: 5px; /* 将发送时间与文本分隔开 */
}

.ownMessage {
    flex-direction: row-reverse;
    align-items: flex-end; /* 将发送时间放置在最下方的贴右位置 */
}

.otherMessage {
    flex-direction: row;
    align-items: flex-end; /* 将发送时间放置在最下方的贴左位置 */
}

.online-dot {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 10px;
    height: 10px;
    background-color: #01c201;
    border-radius: 50%;
}
.offline-dot {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 10px;
    height: 10px;
    background-color: #999;
    border-radius: 50%;
}
.message-badge .el-badge__content {
    position: absolute;
    bottom: 5px; /* Adjust to your desired position */
    left: 5px; /* Adjust to your desired position */
    background-color: #f56c6c; /* Red background for visibility */
    color: white; /* White text color */
}
</style>


